package org.example.strategy;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 自定精准分片 (分库)
 * @author shenguangyang
 */
public class CustomDbPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long>  {
    /**
     *
     * @param dataSourceNames 数据源集合
     *                   在分库时值为所有分片库的集合
     *                   分表时为对应分片库中所有分片表的集合
     * @param preciseShardingValue 分片属性, 包括
     *                             loginTableName: 逻辑表
     *                             columnName: 分片键(字段)
     *                             value: 为从SQL中解析出的分片键的值
     */
    @Override
    public String doSharding(Collection<String> dataSourceNames, PreciseShardingValue<Long> preciseShardingValue) {
        for (String dataSourceName : dataSourceNames) {
            String value = preciseShardingValue.getValue() % dataSourceNames.size() + "";
            // my_shop_db_0
            if (dataSourceName.endsWith(value)) {
                return dataSourceName;
            }
        }
        throw new IllegalArgumentException();
    }
}
